package com.bjsj.pro.tools;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;
import com.bjsj.pro.R;
import com.bjsj.pro.base.HttpBean;
import com.bjsj.pro.base.MyBaseMvpView;
import com.bjsj.pro.base.view.NetworkLayout;


import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/3/14.
 */

public class MyOkgoUtils
{

    public static MyOkgoUtils myOkhttpConnet;
    private static int k;
    private static int y;
    private static int x;
    private GlobalTools tools = GlobalTools.getInstance();
    public static MyOkgoUtils newInstance()
    {
        k=0;
        y=0;
        x=0;
        if (myOkhttpConnet == null)
        {
            synchronized (MyOkgoUtils.class)
            {
                myOkhttpConnet = new MyOkgoUtils();
            }
        }
        return myOkhttpConnet;
    }

    /**
     * 查看网络是否连通
     * <p/>
     * if(info.getType() == ConnectivityManager.TYPE_WIFI){ state=2;//wifi网络
     * }else{ state=3;//其他移动或者联通网络。 }
     */
    public int isNetConnecteds(Context context)
    {
        int state;
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable())
        {
            state = 1;
        } else
        {
            state = 0;
        }
        return state;
    }


    /**
     *
     */
    public <T> void startHttpRequest(final Activity context, final HttpBean mHttpBean, final Class<T> classOfT, final MyBaseMvpView<T> iBaseMvpView)
    {

        startRequestData(context, mHttpBean, classOfT, iBaseMvpView);
        if (mHttpBean.getGetType()==Configs.OKGO_GET_TYPE_NETWORKLAYOUT)
        {
            mHttpBean.getFailnetworkd().setOnReloadListeners(new NetworkLayout.NoNetWorkLayoutCallback()
            {
                @Override
                public void reloadData()
                {
                    startRequestData(context,mHttpBean, classOfT, iBaseMvpView);
                }
            });
        }

    }

    private <T> void startRequestData(final Activity context, final HttpBean mHttpBean, final Class<T> classOfT,
                                      final MyBaseMvpView<T> iBaseMvpView)
    {


        int netConnecteds = isNetConnecteds(context);
        if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_NETWORKLAYOUT)
        {
            mHttpBean.getFailnetworkd().setAgainGetMsg();
        }

        if (netConnecteds == 0)

        {
            if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_NETWORKLAYOUT)
            {
                mHttpBean.getFailnetworkd().setNonetWorkVisible();
                mHttpBean.getFailnetworkd().setNetworkErroMsg(context.getString(R.string.wuwangluo));
                iBaseMvpView.onfailShow(context.getString(R.string.wuwangluo));
            }

            tools.showToast(context, context.getString(R.string.wuwangluo));

            return;
        }
        tools.logD("请求的url:" + mHttpBean.getHttpurl());

        if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_PROGRESS)
        {
            tools.showProgress(context);
        }
        //获取缓存的语言
        /*SharedPreferences sp = tools.getSpInstance(context, "Language");
        int country = sp.getInt("country", 85);
        mHttpBean.setYuyan(country);*/

        BaseRequest mBaseRequest;

        //定义okgo的请求方式
        int httpGetType = mHttpBean.getHttpGetType();
        switch (httpGetType)
        {
            case Configs.OKGO_POST:
                mBaseRequest = OkGo.post(mHttpBean.getHttpurl());
                break;
            case Configs.OKGO_GET:
                mBaseRequest = OkGo.get(mHttpBean.getHttpurl());
                break;
            case Configs.OKGO_DEL:
                mBaseRequest = OkGo.delete(mHttpBean.getHttpurl());
                break;
            case Configs.OKGO_PUT:
                mBaseRequest = OkGo.put(mHttpBean.getHttpurl());
                break;
            default:
                mBaseRequest = OkGo.post(mHttpBean.getHttpurl());
                break;
        }

         tools.logD("=========token:" + mHttpBean.getToken());
          mBaseRequest.tag(context)
                .params(mHttpBean.getHttpParams())
                .headers("TICKET",mHttpBean.getToken())
                .headers("HTTP_USER_SYSTEM","XBS_APP")
                .execute(new StringCallback()
                {
                    @Override
                    public void onSuccess(String s, Call call, Response response)
                    {

                        if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_NETWORKLAYOUT)
                        {
                            mHttpBean.getFailnetworkd().setHasGetMsgVisible();
                        }
                        i("后台返回的json:" + s);

                        try
                        {
                            JSONObject jsonObject = new JSONObject(s);
                            int code = jsonObject.optInt("code");
                            String message = jsonObject.optString("msg");
                            tools.logD("ttttttttttttttt" + message);
                            switch (code)
                            {
                                case 100:
                                    //请求成功
                                    if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_NETWORKLAYOUT)
                                    {
                                        mHttpBean.getFailnetworkd().setHasGetMsgVisible();
                                    }
                                    T t = new Gson().fromJson(s,classOfT);
                                    iBaseMvpView.onSuccessShowData(t);
                                    break;
                                case -102:
                                    //token失效
                                  //  tools.logD("=========token:" + mHttpBean.getToken());
//                                    if(x==0) {
//                                        tools.showToast(context, message);
//                                        if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_NETWORKLAYOUT) {
//                                            mHttpBean.getFailnetworkd().setNonetWorkVisible();
//                                        }
//                                        String tishi=context.getString(R.string.tishi);
//                                        String msg = message;
//                                        String quxiao = context.getString(R.string.quxiao);
//                                        String queding = context.getString(R.string.queding);
//                                        new AlertDialog.Builder(context).setTitle(tishi)
//                                                .setMessage(message)
//                                                .setNegativeButton(quxiao, new DialogInterface.OnClickListener() {
//                                                    @Override
//                                                    public void onClick(DialogInterface dialogInterface,int i) {
//
//                                                    }
//                                                })
//                                                .setPositiveButton(queding, new DialogInterface.OnClickListener() {
//                                                    @Override
//                                                    public void onClick(DialogInterface dialogInterface, int i) {
//                                                        tools.saveObject(context, Configs.SAVE_LOGIN_KEY, Configs.SAVE_LOGIN_SP_NAME, null);
//                                                        MainShowView mMainShowView = new MainShowView();
//                                                        mMainShowView.setShowView(101);
//                                                        // EventBus.getDefault().post(mMainShowView);
//                                                        //  EventBus.getDefault().post(new SysyemMsgNum(0));
//                                                        TourismApp.getAppInstance().exitAppExceptMain();
//                                                        context.startActivity(new Intent(context, LoginActivity.class));
//                                                    }
//                                                }).show();
//                                            x++;
//                                    }
                                    break;
                                case -104:
                                    if(k==0) {
                                        if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_NETWORKLAYOUT) {
                                            mHttpBean.getFailnetworkd().setNonetWorkVisible();
                                        }
//                                    String tishi1 = context.getString(R.string.tishi);
//                                    String msg1 = context.getString(R.string.denglushixiao);
//                                    String quxiao1 = context.getString(R.string.quxiao);
//                                    String queding1 = context.getString(R.string.queding);
//                                    Intent intent = new Intent(context, IsBindActivity.class);
//                                    context.startActivity(intent);
//                                        k++;
//                                    }
                                    }
                                    break;
                                case -105:
                                  //  startActivity(new Intent(this,InvitationActivity.class));
//                                    if(y==0){
//                                        Intent intent = new Intent(context, InvitationActivity.class);
//                                        context.startActivity(intent);
//                                        y++;
//                                    }
                                    break;
                                default:
                                    //其他请求失败情况
                                    Log.d("错误信息",message);
                                    tools.showToast(context, message);
                                    if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_NETWORKLAYOUT)
                                    {
                                        mHttpBean.getFailnetworkd().setNetworkErroMsg(message);
                                        mHttpBean.getFailnetworkd().setNonetWorkVisible();
                                    }
                                    iBaseMvpView.onfailShow(message);
                                    break;
                            }
//                        GlobalTools.getInstance().logD("============2=="+s);

                        } catch (JSONException e)
                        {
                            e.printStackTrace();
                        }

                        if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_PROGRESS)
                        {
                            tools.hideProgress();
                        }

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e)
                    {
                        super.onError(call, response, e);
                        if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_NETWORKLAYOUT)
                        {
                            mHttpBean.getFailnetworkd().setNonetWorkVisible();
                        }
                        if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_PROGRESS)
                        {
                            tools.hideProgress();
                        }

                        if (isNetConnecteds(context) == 0)
                        {
                            if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_NETWORKLAYOUT)
                            {
                                //没有网络
                                mHttpBean.getFailnetworkd().setNetworkErroMsg(context.getString(R.string.wuwangluo));
                                mHttpBean.getFailnetworkd().setNetworkImage(R.drawable.wifi);
                            }
                            tools.showToast(context, context.getString(R.string.wuwangluo));


                        } else
                        {
                            if (mHttpBean.getGetType() == Configs.OKGO_GET_TYPE_NETWORKLAYOUT)
                            {
                                //请求服务器失败
                                mHttpBean.getFailnetworkd().setNetworkErroMsg(context.getString(R.string.lianjiefuwuqiyic));
                                mHttpBean.getFailnetworkd().setNetworkImage(R.drawable.kong);
                            }
                            tools.showToast(context, context.getString(R.string.lianjiefuwuqiyic));
                        }
                    }
                });
    }


    private void i(String msg)
    {  //信息太长,分段打印
        //因为String的length是字符数量不是字节数量所以为了防止中文字符过多，
        //  把4*1024的MAX字节打印长度改为2001字符数
        int max_str_length = 2001;
        //大于4000时
        while (msg.length() > max_str_length)
        {
            tools.logD(msg.substring(0, max_str_length));
            msg = msg.substring(max_str_length);
        }
        //剩余部分
        tools.logD(msg);
    }


}
